package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuBoundsTo;
import com.atguigu.common.to.SkuEsModel;
import com.atguigu.common.to.SkuFullReductionTo;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.HasStockVo;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.SearchFeign;
import com.atguigu.gulimall.product.feign.SmsService;
import com.atguigu.gulimall.product.feign.WareFeign;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeign wareFeign;
    @Autowired
    private SearchFeign searchFeign;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    //SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
    public void savePublishProduct(SpuSaveVo spuSaveVo) {
        //保存pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        Long brandId = spuSaveVo.getBrandId();
        Long catalogId = spuSaveVo.getCatalogId();
        spuInfoEntity.setPublishStatus(ProductConstant.ProductStatusEnum.NEW_CREATE.getCode());
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        this.save(spuInfoEntity);
        Long spuId = spuInfoEntity.getId();
        //保存pms_spu_info_desc
        List<String> decript = spuSaveVo.getDecript();
        if(decript!=null){
            String join = String.join(",", decript);
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuId);
            spuInfoDescEntity.setDecript(join);
            spuInfoDescService.save(spuInfoDescEntity);
        }

        //保存pms_spu_images
        List<String> images = spuSaveVo.getImages();
        List<SpuImagesEntity> spuImagesEntities = images.stream().map(image -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuId);
            spuImagesEntity.setImgUrl(image);
            spuImagesEntity.setImgSort(0);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(spuImagesEntities);

        //保存sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SkuBoundsTo skuBoundsTo = new SkuBoundsTo();
        BeanUtils.copyProperties(bounds,skuBoundsTo);
        skuBoundsTo.setSpuId(spuId);
        smsService.save(skuBoundsTo);

        //保存pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            //查询attr的name
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            productAttrValueEntity.setSpuId(spuId);
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        //保存pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        skus.stream().forEach(sku->{

            List<Images> images1 = sku.getImages();
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(sku,skuInfoEntity);
            skuInfoEntity.setBrandId(brandId);
            skuInfoEntity.setSpuId(spuId);
            skuInfoEntity.setCatalogId(catalogId);
            images1.forEach(i->{
                if(i.getDefaultImg()==1){
                    skuInfoEntity.setSkuDefaultImg(i.getImgUrl());
                }
            });
            skuInfoService.save(skuInfoEntity);

            //保存pms_sku_images
            List<SkuImagesEntity> skuImagesEntities = images1.stream().filter(image ->{
                return !StringUtils.isBlank(image.getImgUrl());
            }).map(i -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setImgUrl(i.getImgUrl());
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                return skuImagesEntity;
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);

            //保存pms_sku_sale_attr_value
            List<Attr> attrs = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                //查询attr的name
                AttrEntity attrEntity = attrService.getById(attr.getAttrId());
                BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                skuSaleAttrValueEntity.setAttrName(attrEntity.getAttrName());
                return skuSaleAttrValueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            //保存sms满减等信息
            SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();

            BeanUtils.copyProperties(sku,skuFullReductionTo);
            skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
            smsService.saveSkuFullReduction(skuFullReductionTo);
        });
    }

    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        String key = (String) params.get("key");
        String brandId = (String) params.get("brandId");
        String catelogId = (String) params.get("catelogId");
        if(status!=null){
            queryWrapper.eq("publish_status",status);
        }
        if(brandId!=null && !"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        if(catelogId!=null && !"0".equals(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }
        if(!org.springframework.util.StringUtils.isEmpty(key)){
            queryWrapper.and(wrapper->{
                wrapper.eq("id",key).or().like("spu_name",key);
            });
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void productUp(Long spuId) {
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        List<Long> skuIds = skuInfoEntityList.stream().map(skuInfoEntity -> {
            return skuInfoEntity.getSkuId();
        }).collect(Collectors.toList());
        //检索可查询到的属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.listforspu(spuId);
        List<Long> attrIds = productAttrValueEntities.stream().map(productAttrValueEntity -> {
            return productAttrValueEntity.getAttrId();
        }).collect(Collectors.toList());

        List<AttrEntity> attrEntityList = attrService.listByIds(attrIds);

        List<Long> searchedIds = attrEntityList.stream().filter(attrEntity -> {
            return attrEntity.getSearchType() == 1;
        }).map(attrEntity -> {
            return attrEntity.getAttrId();
        }).collect(Collectors.toList());

        Set<Long> ids = searchedIds.stream().collect(Collectors.toSet());

        List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter(productAttrValueEntity -> {
            return ids.contains(productAttrValueEntity.getAttrId());
        }).map(productAttrValueEntity -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(productAttrValueEntity, attrs);

            return attrs;
        }).collect(Collectors.toList());

        //查询有无库存
        R hasStock = wareFeign.hasStock(skuIds);

        TypeReference<List<HasStockVo>> typeReference = new TypeReference<List<HasStockVo>>(){};
        Map<Long,Boolean> map = hasStock.getData(typeReference).stream().collect(Collectors.toMap(HasStockVo::getSkuId,hasStockVo -> hasStockVo.getHasStock()));
        //保存skuEsModel
        List<SkuEsModel> skuEsModelList = skuInfoEntityList.stream().map(skuInfoEntity -> {

            SkuEsModel skuEsModel = new SkuEsModel();

            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setSaleCount(skuInfoEntity.getSaleCount()==null?0:skuInfoEntity.getSaleCount());
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            skuEsModel.setHotScore(0L);
            //查询品牌、分类
            CategoryEntity categoryEntity = categoryService.getById(skuInfoEntity.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            BrandEntity brandEntity = brandService.getById(skuInfoEntity.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());

            //设置属性
            skuEsModel.setAttrs(attrsList);

            //设置有误库存
            skuEsModel.setHasStock(map.get(skuInfoEntity.getSkuId())==null?false:true);

            return skuEsModel;
        }).collect(Collectors.toList());


        //存储到es
        R up = searchFeign.up(skuEsModelList);
        if(up.getCode()==0){
            //更新状态
            this.update(new UpdateWrapper<SpuInfoEntity>().eq("id",spuId).set("publish_status",ProductConstant.ProductStatusEnum.PRODUCT_UP.getCode()));
        }else {
            //重复调用？接口幂等性:重试机制
        }
    }

    @Override
    public SpuInfoVo getSpuEntityWithSkuId(Long skuId) {
        SpuInfoVo spuInfoVo = this.baseMapper.getSpuEntityWithSkuId(skuId);
        return spuInfoVo;
    }
}